import { defineStore } from 'pinia';
import { ref, type Ref } from 'vue';

interface DynamicObject {
  [key: string]: any;
}

export const useTagsViewStore = defineStore('TagsView', () => {
  const visitedViews: Ref<DynamicObject[]> = ref([]);
  const cachedViews: Ref<DynamicObject[]> = ref([]);
  // 添加tag
  function setTagsView(view: DynamicObject) {
    const isHasView: boolean = visitedViews.value.some((v: DynamicObject) => {
      return v.path === view.path;
    });

    if (isHasView) {
      return false;
    }
    visitedViews.value.push(Object.assign({}, view));
  }

  // 删除tag
  function delTagsView(view: DynamicObject) {
    return new Promise((resolve) => {
      for (const [i, v] of visitedViews.value.entries()) {
        if (v.path === view.path) {
          visitedViews.value.splice(i, 1);
          break;
        }
      }
      resolve(visitedViews.value);
    });
  }

  // 刷新页面
  function delCachedView(view: DynamicObject) {
    return new Promise((resolve) => {
      const index = cachedViews.value.findIndex((value) => {
        return value.path === view.path;
      });
      index > -1 && cachedViews.value.splice(index, 1);
      resolve(cachedViews.value);
    });
  }

  // 删除其它tag
  function delOthersVisitedViews(view: DynamicObject) {
    visitedViews.value = visitedViews.value.filter((v) => {
      return v.path === view.path;
    });
  }

  // 删除所有tag
  function delAllVisitedViews() {
    visitedViews.value = [];
  }

  // 更新tags
  function updateVisitedView(view: DynamicObject) {
    for (let v of visitedViews.value) {
      if (v.path === view.path) {
        v = Object.assign(v, view);
        break;
      }
    }
  }

  return {
    visitedViews,
    cachedViews,
    setTagsView,
    delTagsView,
    delCachedView,
    delOthersVisitedViews,
    delAllVisitedViews,
    updateVisitedView
  };
});
